﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sispe.Entities;
using Sispe.BussinesLogic;
using Microsoft.Practices.Unity;


namespace Sispe.Mvc4.Controllers
{
    public class TareoController : Controller
    {
        [Dependency]
        public IPersonaBL personaBL { get; set; }

        [Dependency]
        public IContratoBL contratoBL { get; set; }

        [Dependency]
        public ITareoBL tareoBL { get; set; }

        //Create Standalone SDK class dynamicly.
        //public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
        public zkemkeeper.CZKEM axCZKEM1 = new zkemkeeper.CZKEM();
        //List<TAREO_BORRADOR> tareoBorrador = null;


        //
        // GET: /Tareo/


        public ActionResult Index()
        {
            ViewData["btnName"] = "Descargar Registro"; 
            ViewData["estadoDevice"] = "Desconectado";
            return View();
        }


        /********************************************************************************************************************************************
        * Before you refer to this demo,we strongly suggest you read the development manual deeply first.                                           *
        * This part is for demonstrating the communication with your device.There are 3 communication ways: "TCP/IP","Serial Port" and "USB Client".*
        * The communication way which you can use duing to the model of the device.                                                                 *
        * *******************************************************************************************************************************************/
        //#region Communication
        //private bool bIsConnected = false;//the boolean value identifies whether the device is connected
        private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.

        //If your device supports the TCP/IP communications, you can refer to this.
        //when you are using the tcp/ip communication,you can distinguish different devices by their IP address.


        //int idwErrorCode = 0;

        //Cursor = Cursors.WaitCursor;
        //if (btnConnect.Text == "Desconectar")
        //{
        //    axCZKEM1.Disconnect();
        //    bIsConnected = false;
        //    btnConnect.Text = "Conectar";
        //    lblState.Text = "Estado del Dispositivo: Desconectado.";
        //    lblState.ForeColor = Color.Crimson;
        //    Cursor = Cursors.Default;
        //    return;
        //}

        //bIsConnected = axCZKEM1.Connect_Net(txtIP.Text, Convert.ToInt32(txtPort.Text));
        //if (bIsConnected == true)
        //{
        //    btnConnect.Text = "Desconectar";
        //    btnConnect.Refresh();
        //    lblState.Text = "Estado del Dispositivo: Conectado";
        //    lblState.ForeColor = Color.Green;
        //    iMachineNumber = 1;//In fact,when you are using the tcp/ip communication,this parameter will be ignored,that is any integer will all right.Here we use 1.
        //    axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
        //}
        //else
        //{
        //    axCZKEM1.GetLastError(ref idwErrorCode);
        //    MessageBox.Show("No se puede conectar con el Dispositivo, ErrorCode=" + idwErrorCode.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //}
        //Cursor = Cursors.Default;


        
        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            var direccionIp = collection["direccionIp"].ToString();
            var puerto = collection["puerto"].ToString();

            var conectado = collection["conectado"].ToString();
                        
            if (conectado == "")
            {
                conectado = "0";
            }

            var bIsConnected = false;


            if (conectado == "0")
            {
                ViewData["direccionIp"] = direccionIp.ToString();
                ViewData["puerto"] = puerto.ToString();
                
                bIsConnected = axCZKEM1.Connect_Net(direccionIp.ToString(),
                Convert.ToInt32(puerto.ToString()));

                if (bIsConnected)
                {
                    axCZKEM1.RegEvent(iMachineNumber, 65535);
                    //Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)


                    string sdwEnrollNumber = "";
                    int idwTMachineNumber = 0;
                    int idwEMachineNumber = 0;
                    int idwVerifyMode = 0;
                    int idwInOutMode = 0;
                    int idwYear = 0;
                    int idwMonth = 0;
                    int idwDay = 0;
                    int idwHour = 0;
                    int idwMinute = 0;
                    int idwSecond = 0;
                    int idwWorkcode = 0;

                    int idwErrorCode = 0;
                    int iGLCount = 0;
                    int iIndex = 0;
                    int iValue = 0;
                    var tareoBorrador = new List<TAREO_BORRADOR>();
                    var msg = "ERROR";

                    //Cursor = Cursors.WaitCursor;
                    //lvLogs.Items.Clear();
                    axCZKEM1.EnableDevice(iMachineNumber, false);//disable the device
                    if (axCZKEM1.ReadGeneralLogData(iMachineNumber))//read all the attendance records to the memory
                    {
                        while (axCZKEM1.SSR_GetGeneralLogData(iMachineNumber, out sdwEnrollNumber, out idwVerifyMode,
                                   out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkcode))//get records from the memory
                        {
                            iGLCount++;
                            var tareo = new TAREO_BORRADOR()
                            {
                                EnrollNumber = sdwEnrollNumber,
                                VerifyMode = idwVerifyMode,
                                InOutMode = idwInOutMode,
                                Date = Convert.ToDateTime(idwYear.ToString() + "/" + idwMonth.ToString() + "/" + idwDay.ToString() + " " +
                                                          idwHour.ToString() + ":" + idwMinute.ToString() + ":" + idwSecond.ToString()),
                                WorkCode = idwWorkcode,
                                Reserved = 0,
                                Existe = false,
                                Contrato = false,
                                Estado = false,
                                Tareo = false
                            };
                            tareoBorrador.Add(tareo);
                            iIndex++;
                        }

                        #region
                        try
                        {
                            //Una vez guardada la lista de Tareos pasamos a revisar los datos
                            foreach (var item in tareoBorrador)
                            {
                                //item.EnrollNumber = Evaluar DNI para ver si existe la persona en la BD
                                var persona = personaBL.GetFromPersonaByDni(item.EnrollNumber);

                                if (persona != null)
                                {
                                    item.Existe = true;

                                    //Ahora vemos si la persona en si tiene un contrato vigente.
                                    var contrato = contratoBL.GetFromContratosPorVencerByIdTrabajador(persona.IdPersona);

                                    if (contrato != null)
                                    {
                                        item.Contrato = true;
                                        item.Estado = true;
                                    }
                                }

                                tareoBL.AddTareoBorrador(item);
                            }
                            //Limpiamos Registro del dispositivo
                            axCZKEM1.EnableDevice(iMachineNumber, false);//disable the device
                            if (axCZKEM1.ClearGLog(iMachineNumber))
                            {
                                axCZKEM1.RefreshData(iMachineNumber);//the data in the device should be refreshed
                                if (axCZKEM1.GetDeviceStatus(iMachineNumber, 6, ref iValue)) //Here we use the function "GetDeviceStatus" to get the record's count.The parameter "Status" is 6.
                                {
                                    var mensaje = "Operacion Completada";
                                    TempData["AlertMessage"] = mensaje;
                                    axCZKEM1.Disconnect();
                                    ViewData["btnName"] = "Registro Descargado";
                                    ViewData["estadoDevice"] = "Desconectado";
                                    return View();
                                }
                            }
                            else
                            {
                                axCZKEM1.GetLastError(ref idwErrorCode);
                            }
                            axCZKEM1.EnableDevice(iMachineNumber, true);//enable the device                    
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                            TempData["AlertMessage"] = msg;
                            return View();
                        }
                        #endregion

                    }
                    else
                    {
                        //Cursor = Cursors.Default;
                        axCZKEM1.GetLastError(ref idwErrorCode);

                        if (idwErrorCode != 0)
                        {
                            var mensaje = "Error al tratar de leer los datos del Dispositivo";
                            TempData["AlertMessage"] = mensaje;
                            axCZKEM1.Disconnect();
                            ViewData["btnName"] = "Descargar Registro";
                            ViewData["estadoDevice"] = "Desconectado";
                            return View();
                        }
                        else
                        {
                            var mensaje = "No existe registro alguno a descargar del dispositivo";
                            TempData["AlertMessage"] = mensaje;
                            axCZKEM1.Disconnect();
                            ViewData["btnName"] = "Descargar Registro";
                            ViewData["estadoDevice"] = "Desconectado";
                            return View();
                        }
                    }
                    axCZKEM1.EnableDevice(iMachineNumber, true);//enable the device
                    //Cursor = Cursors.Default;


                    axCZKEM1.Disconnect();
                    
                    var mensaje1 = "Datos Descargados";
                    TempData["AlertMessage"] = mensaje1;
                    ViewData["btnName"] = "Descargar Registro";
                    ViewData["estadoDevice"] = "Desconectado";
                    return View();

                }
                else
                {
                    var mensaje = "Operacion Completada";
                    TempData["AlertMessage"] = mensaje;
                    ViewData["btnName"] = "Descargar Registro";
                    ViewData["estadoDevice"] = "Desconectado";
                    return View();
                }
                
            }
            return View();
            ViewData["btnName"] = "Descargar Registro";
            ViewData["estadoDevice"] = "Desconectado";

        }

    }
}
